package com.dudu.access;

import java.util.Calendar;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.dudu.bean.DialResultBean;
import com.dudu.bean.ResponseSendVoiceBean;
import com.dudu.enumeration.RemindEnum;
import com.dudu.service.ILogService;
import com.dudu.service.impl.LogService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.Encrypt;
import com.dudu.utils.HttpRequest;
import com.dudu.utils.SsoUtil;

/**
 * 用友自建平台接口工具类
 * 
 * @author gaoxs
 * 
 */
public class YonYouUtil {
    private static ILogService logService = new LogService(); // ;
    private static final Logger log = Logger.getLogger(YonYouUtil.class);
    private static ResourceBundle resourceBundle = PropertyResourceBundle.getBundle("voicenoticeconfig");
    private static String serverUrl = DictionaryUtils.getValueByTypeAndKey("youyon", "serverUrl");
    private static String secret = DictionaryUtils.getValueByTypeAndKey("youyon", "secret");
    private static String ticketurl = DictionaryUtils.getValueByTypeAndKey("youyon", "ticketUrl");
    private static String statusurl = DictionaryUtils.getValueByTypeAndKey("youyon", "statusUrl");
    private static String bucketName = resourceBundle.getString("bucketName");
    //private static String serverUrl = "http://123.56.19.215/";
    //private static String secret = "cass@dudu";
   // private static String ticketurl = "http://123.103.9.189:5231/yonyoucallback/BillCallBack.do";
    //private static String statusurl = "http://123.103.9.189:5231/yonyoucallback/StatusCallBack.do";

    public static void main(String[] args) {
	// YonYouUtil.VoiceNotice("18662187762", "17001090120", "", "加班吃饭去了",
	// "95078600588", "", "", "先播放前导音", "1", "");
	// YonYouUtil.UploadFile("201702280920232237.mp3");//("17001090120",
	// "music.wav", "", "62434318", "", "", "秀山给你留言:", "1");
	// YonYouUtil.IvrDial("17001090122", "17001090120", "95078600588", "",
	// "满意请按1,不满意请按2", "");
	// YonYouUtil.dial("17001090122", "18662187762", "95078600588", "", "",
	// "0");
	//YonYouUtil.dialStop("2461bb73-7f46-4101-8ac1-8ab4fd8bbb56");
	YonYouUtil.textToSpeech("一个女生没谈恋爱，身边的朋友有谈了的也有没谈的，那这很正常。但如果身边的朋友都谈恋爱了，就你一个单身，那你自己可要反思反思了，很有可能是你自己的美色吸引好多异性，然后他们为了接近你就和你身边朋友谈恋爱了");
    }

    /**
     * IVR外呼
     * 
     * @param caller
     *            主叫
     * @param called
     *            被叫
     * @param displayNum
     *            显号
     * @param mediaName
     *            语音文件名
     * @param mediaTxt
     *            文字
     * @param tts_content
     *            前导音
     * @return
     */
    public static ResponseSendVoiceBean IvrDial(String caller, String called, String displayNum, String mediaName, String mediaTxt, String tts_content) {
	ResponseSendVoiceBean responseSendVoice = new ResponseSendVoiceBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject requestBody = new JSONObject();// 请求参数
	String sessionid = UUID.randomUUID().toString();
	String responsedata = "";
	String result = "-1";
	String desc = "";
	try {
	    String timestmap = String.valueOf(System.currentTimeMillis());
	    JSONArray voiceArray = new JSONArray();// 请求参数 父参数announcement
	    JSONObject voiceText = new JSONObject(); // 文字正文 父参数voiceArray
	    JSONObject voiceMedia = new JSONObject(); // 语音文件父参数voiceArray
	    if (StringUtils.isBlank(mediaName) && StringUtils.isNotBlank(mediaTxt)) {
		voiceText.put("voiceType", "text");
		voiceText.put("content", mediaTxt);
	    } else if (StringUtils.isBlank(mediaTxt) && StringUtils.isNotBlank(mediaName)) {
		voiceText.put("voiceType", "file");
		voiceText.put("content", mediaName);
	    } else if (StringUtils.isNotBlank(mediaTxt) && StringUtils.isNotBlank(mediaName)) {
		voiceText.put("voiceType", "text");
		voiceText.put("content", mediaTxt);
		voiceMedia.put("voiceType", "file");
		voiceMedia.put("content", mediaName);
		voiceMedia.put("index", "0");
		voiceArray.add(voiceMedia);
	    }
	    voiceText.put("index", "0");
	    voiceArray.add(voiceText);
	    JSONObject ivr = new JSONObject();// 请求参数 父参数requestArray
	    ivr.put("serial", sessionid);
	    ivr.put("caller", displayNum); // 显号
	    ivr.put("called", called);
	    ivr.put("originalCaller", caller); // 原始主叫号码
	    ivr.put("announcements", voiceArray);
	    ivr.put("callEventUrl", statusurl);
	    ivr.put("callRecordUrl", ticketurl);

	    JSONObject voiceTts = new JSONObject(); // 前导音Voice
	    if (StringUtils.isBlank(tts_content)) {
		tts_content = "{}";
	    }
	    if (StringUtils.isNotBlank(tts_content)) {
		voiceTts.put("voiceType", "text");
		voiceTts.put("content", tts_content);
	    }
	    ivr.put("leadingVoice", voiceTts);// 前导音
	    ivr.put("priority", 2);// 优先级1=普通 2=重要
	    ivr.put("ttsParams", "");
	    JSONArray requestArray = new JSONArray();// 请求参数 父参数requestBody
	    requestArray.add(ivr);// 请求参数 父参数requestBody
	    requestBody.put("sign", Encrypt.md5Encrypt("time=" + timestmap + "&secret=" + secret).toUpperCase()); // 签名
	    requestBody.put("time", timestmap);// 发送时间
	    requestBody.put("requestCount", 1);// 呼叫个数
	    requestBody.put("requests", requestArray);// 呼叫任务
	    String Myurl = serverUrl + "ivr/v1/ivr";
	    log.info("YonYouUtil.IvrDial req url=" + Myurl + ";request=" + requestBody.toString());
	    responsedata = HttpRequest.postData(Myurl, requestBody.toString());
	    remind(responsedata, RemindEnum.OPEN_IVRDIAL_YONYOU.getKey(), RemindEnum.OPEN_IVRDIAL_YONYOU.getValue()+"called:"+called);
	    log.info("YonYouUtil.IvrDial response " + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("status");
		desc = response.optString("msg");
		if (result.equals("000000")) {
		    result = "0";
		}
	    } else {
		responsedata = "";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    responseSendVoice.setResult("9999");
	    responseSendVoice.setDesc(e.getMessage());
	    responseSendVoice.setSessionid("");
	    return responseSendVoice;
	}
	long end = Calendar.getInstance().getTimeInMillis();
	Double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "YonYouIvrDail", "【" + requestBody.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "YonYou", called);
	responseSendVoice.setResult(result);
	if (result.equals("0")) {
	    responseSendVoice.setSessionid(sessionid);
	} else {
	    responseSendVoice.setSessionid("");
	}

	responseSendVoice.setDesc(desc);
	return responseSendVoice;
    }

    /**
     * 外呼（语音通知）
     * 
     * @param called
     *            外呼号码
     * @param mediaName
     *            外呼内容：语音
     * @param mediaTxt
     *            外呼内容：文字
     * @param displayNum
     *            显号
     * @param respUrl
     *            状态URL
     * @param ticketUrl
     *            话单URL
     * @param tts_content
     *            前导音
     * @param priority
     *            优先级1=普通 2=重要
     * 
     * @return
     */
    public static ResponseSendVoiceBean VoiceNotice(String caller, String called, String mediaName, String mediaTxt, String displayNum, String respUrl, String ticketUrl,
	    String tts_content, String priority, String repeat) {
	ResponseSendVoiceBean responseSendVoice = new ResponseSendVoiceBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject requestBody = new JSONObject();// 请求参数
	JSONArray requestArray = new JSONArray();// 请求参数 父参数requestBody
	String sessionid = UUID.randomUUID().toString();
	String responsedata = "";
	String result = "-1";
	String desc = "";
	try {
	    if (StringUtils.isBlank(repeat)) {
		repeat = "3";
	    }
	    String timestmap = String.valueOf(System.currentTimeMillis());
	    JSONArray voiceArray = new JSONArray();// 请求参数 父参数announcement
	    JSONObject voiceText = new JSONObject(); // 文字正文 父参数voiceArray
	    JSONObject voiceMedia = new JSONObject(); // 语音文件父参数voiceArray
	    JSONObject voiceTts = new JSONObject(); // 前导音Voice
	    if (StringUtils.isBlank(mediaName) && StringUtils.isNotBlank(mediaTxt)) {
		voiceText.put("voiceType", "text");
		voiceText.put("content", mediaTxt);
	    } else if (StringUtils.isBlank(mediaTxt) && StringUtils.isNotBlank(mediaName)) {
		voiceText.put("voiceType", "file");
		voiceText.put("content", mediaName);
	    } else if (StringUtils.isNotBlank(mediaTxt) && StringUtils.isNotBlank(mediaName)) {
		voiceText.put("voiceType", "text");
		voiceText.put("content", mediaTxt);
		voiceMedia.put("voiceType", "file");
		voiceMedia.put("content", mediaName);
		voiceMedia.put("index", "0");
		voiceArray.add(voiceMedia);
	    }
	    voiceText.put("index", "0");
	    voiceArray.add(voiceText);
	    JSONObject announcement = new JSONObject();// 请求参数 父参数requestArray
	    announcement.put("serial", sessionid);
	    announcement.put("caller", displayNum); // 显号
	    announcement.put("called", called);
	    announcement.put("originalCaller", caller); // 原始主叫号码
	    announcement.put("announcements", voiceArray);
	    announcement.put("repeat", repeat);// 播放次数
	    if (StringUtils.isBlank(respUrl)) {
		respUrl = statusurl;
	    }
	    announcement.put("callEventUrl", respUrl);
	    if (StringUtils.isBlank(ticketUrl)) {
		ticketUrl = ticketurl;
	    }
	    announcement.put("callRecordUrl", ticketUrl);
	    announcement.put("repeatType", "2");// 重播类型1：自动重播 2：按键重播
	    announcement.put("priority", priority);// 优先级1=普通 2=重要
	    if (StringUtils.isBlank(tts_content)) {
		tts_content = "{}";
	    }
	    if (StringUtils.isNotBlank(tts_content)) {
		voiceTts.put("voiceType", "text");
		voiceTts.put("content", tts_content);
	    }
	    announcement.put("leadingVoice", voiceTts);// 前导音
	    announcement.put("ttsParams", "");
	    requestArray.add(announcement);// 请求参数 父参数requestBody
	    requestBody.put("sign", Encrypt.md5Encrypt("time=" + timestmap + "&secret=" + secret).toUpperCase()); // 签名
	    requestBody.put("time", timestmap);// 发送时间
	    requestBody.put("requestCount", 1);// 呼叫个数
	    requestBody.put("requests", requestArray);// 呼叫任务
	    String Myurl = serverUrl + "ivr/v1/announce";
	    log.info("YonYouUtil.VoiceNotice req url=" + Myurl + ";request=" + requestBody.toString());
	    responsedata = HttpRequest.postData(Myurl, requestBody.toString());
	    remind(responsedata, RemindEnum.OPEN_VOICE_YONYOU.getKey(), RemindEnum.OPEN_VOICE_YONYOU.getValue()+"called:"+called);
	    log.info("YonYouUtil.VoiceNotice response " + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("status");
		desc = response.optString("msg");
		if (result.equals("000000")) {
		    result = "0";
		} else {
		    result = "-1";
		}
	    } else {
		responsedata = "";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    responseSendVoice.setResult("9999");
	    responseSendVoice.setDesc(e.getMessage());
	    responseSendVoice.setSessionid("");
	    return responseSendVoice;
	}
	long end = Calendar.getInstance().getTimeInMillis();
	Double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "YonYouNotice", "【" + requestBody.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "YonYou", called);
	responseSendVoice.setResult(result);
	if (result.equals("0")) {
	    responseSendVoice.setSessionid(sessionid);
	} else {
	    responseSendVoice.setSessionid("");
	}
	responseSendVoice.setDesc(desc);
	return responseSendVoice;
    }

    /**
     * 文字转语音
     * 
     * @param text
     * @return
     */
    public static ResponseSendVoiceBean textToSpeech(String text) {
	ResponseSendVoiceBean resultbean = new ResponseSendVoiceBean();
	Long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject requestBody = new JSONObject();// 请求参数
	String responsedata = "";
	String result = "-1";
	String desc = "";
	String fileFullName = "";
	try {
	    String url = serverUrl + "tts/v1/speechSynthesizer";
	    String timestmap = String.valueOf(System.currentTimeMillis());
	    requestBody.put("sign", Encrypt.md5Encrypt("time=" + timestmap + "&secret=" + secret).toUpperCase()); // 签名
	    requestBody.put("time", timestmap);// 发送时间
	    requestBody.put("text", text);
	    log.info("YonYouUtil.textToSpeech req url=" + url + ";request=" + requestBody.toString());
	    responsedata = HttpRequest.postData(url, requestBody.toString());
	    remind(responsedata, RemindEnum.OPEN_TTS_YONYOU.getKey(), RemindEnum.OPEN_TTS_YONYOU.getValue());
	    log.info("YonYouUtil.textToSpeech response " + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("status");
		desc = response.optString("msg");
		fileFullName = response.optString("fileFullName");
		if (result.equals("000000")) {
		    result = "0";
		    resultbean.setDownUrl(response.optString("downUrl"));
		} else {
		    result = "-1";
		}
	    } else {
		responsedata = "";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	Long end = Calendar.getInstance().getTimeInMillis();
	Double during = Double.valueOf((end - begin)) / 1000;
	logService
		.logIms(during, "textToSpeech", "textToSpeech-YonYou-" + "【" + requestBody + "】", "【" + responsedata + "】", result + "", DateUtils.getCurrentTime(), "YonYou", "");
	resultbean.setResult(result);
	resultbean.setDesc(desc);
	resultbean.setFileName(fileFullName);
	return resultbean;
    }

    /**
     * 上传文件
     * 
     * @param fileName
     *            文件名
     * @return
     */
    public static ResponseSendVoiceBean UploadFile(String fileName) {
	ResponseSendVoiceBean bean = new ResponseSendVoiceBean();
	Long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject requestBody = new JSONObject();// 请求参数
	String responsedata = "";
	String result = "-1";
	String desc = "";
	try {
	    String url = serverUrl + "file/v1/voiceUpload";
	    String timestmap = String.valueOf(System.currentTimeMillis());
	    requestBody.put("sign", Encrypt.md5Encrypt("time=" + timestmap + "&secret=" + secret).toUpperCase()); // 签名
	    requestBody.put("time", timestmap);// 发送时间
	    requestBody.put("bucketName", bucketName);
	    requestBody.put("voiceFile", fileName);
	    log.info("YonYouUtil.UploadFile req url=" + url + ";request=" + requestBody.toString());
	    responsedata = HttpRequest.postData(url, requestBody.toString());
	    remind(responsedata, RemindEnum.OPEN_UPLOADFILE_YONYOU.getKey(), RemindEnum.OPEN_UPLOADFILE_YONYOU.getValue()+"文件名:"+fileName);
	    log.info("YonYouUtil.UploadFile response " + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("status");
		desc = response.optString("msg");
		if (result.equals("000000")) {
		    result = "0";
		} else {
		    result = "-1";
		}
	    } else {
		responsedata = "";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	Long end = Calendar.getInstance().getTimeInMillis();
	Double during = Double.valueOf((end - begin)) / 1000;
	logService.logIms(during, "UploadFile", "上传文件-YonYou-" + "【" + requestBody + "】", "【" + responsedata + "】", result + "", DateUtils.getCurrentTime(), "YonYou", "");
	bean.setResult(result);
	bean.setDesc(desc);
	bean.setFileName(fileName);
	return bean;
    }

    /**
     * 两方通话
     * 
     * @param caller
     * @param called
     * @param displayNum
     * @param respUrl
     * @param ticketUrl
     * @param needRecord
     * @return
     */
    public static DialResultBean dial(String caller, String called, String displayNum, String needRecord) {
	DialResultBean resultBean = new DialResultBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject requestBody = new JSONObject();// 请求参数
	String sessionid = UUID.randomUUID().toString();
	String responsedata = "";
	String result = "-1";
	String desc = "";
	try {
	    if (StringUtils.isBlank(needRecord)) { // 默认不录音
		needRecord = "0";
	    }
	    String timestmap = String.valueOf(System.currentTimeMillis());
	    requestBody.put("sign", Encrypt.md5Encrypt("time=" + timestmap + "&secret=" + secret).toUpperCase()); // 签名
	    requestBody.put("time", timestmap); // 发送时间
	    requestBody.put("serial", sessionid); // 流水号
	    requestBody.put("caller", caller); // 主叫
	    requestBody.put("called", called); // 被叫
	    requestBody.put("displayCaller", displayNum); // 主叫显号
	    requestBody.put("displayCalled", displayNum); // 被叫显号
	    // requestBody.put("callerName", "callerName"); //主叫名称
	    // requestBody.put("calledName", "calledName"); //被叫名称
	    requestBody.put("needRecord", needRecord); // 0:不录音，1:录音
	    requestBody.put("callEventUrl", statusurl); // 状态回调
	    requestBody.put("callRecordUrl", ticketurl); // 话单回调
	    String Myurl = serverUrl + "call/v1/twoWayCall";
	    log.info("YonYouUtil.dial req url=" + Myurl + ";request=" + requestBody.toString());
	    responsedata = HttpRequest.postData(Myurl, requestBody.toString());
	    remind(responsedata, RemindEnum.OPEN_DIAL_YONYOU.getKey(), RemindEnum.OPEN_DIAL_YONYOU.getValue()+"caller:"+caller+";called:"+called);
	    log.info("YonYouUtil.dial response " + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("status");
		desc = response.optString("msg");
		if (result.equals("000000")) {
		    result = "0";
		} else {
		    result = "-1";
		}
	    } else {
		responsedata = "";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return null;
	}
	long end = Calendar.getInstance().getTimeInMillis();
	Double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "YonYouDial", "【" + requestBody.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "YonYou", called);
	resultBean.setDisplayNbr(displayNum);
	resultBean.setResult(result);
	resultBean.setSessionId(sessionid);
	resultBean.setDesc(desc);
	return resultBean;
    }

    /**
     * 结束通话
     * 
     * @param sessionId
     * @return
     */
    public static JSONObject dialStop(String sessionId) {
	JSONObject object = new JSONObject();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject requestBody = new JSONObject();// 请求参数
	String responsedata = "";
	String result = "-1";
	String desc = "";
	try {
	    String timestmap = String.valueOf(System.currentTimeMillis());
	    requestBody.put("sign", Encrypt.md5Encrypt("time=" + timestmap + "&secret=" + secret).toUpperCase()); // 签名
	    requestBody.put("time", timestmap); // 发送时间
	    requestBody.put("serial", sessionId); // 流水号
	    String Myurl = serverUrl + "call/v1/cancelTwoWayCall";
	    log.info("YonYouUtil.dial req url=" + Myurl + ";request=" + requestBody.toString());
	    responsedata = HttpRequest.postData(Myurl, requestBody.toString());
	    log.info("YonYouUtil.dialStop response " + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("status");
		desc = response.optString("msg");
		if (result.equals("000000")) {
		    result = "0";
		} else {
		    result = "-1";
		}
	    } else {
		result = "-1";
		responsedata = "";
		desc = "接口响应为空";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return null;
	}
	long end = Calendar.getInstance().getTimeInMillis();
	Double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "YonYouDailStop", "【" + requestBody.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "YonYou", "");
	object.put("result", result);
	object.put("discripe", desc);
	return object;
    }

    /**
     * 提醒
     * 
     * @param response
     * @param abilityType
     */
    public static void remind(String response, String abilityType, String content) {
	if (StringUtils.isNotBlank(response)) {
	    JSONObject responsejson = JSONObject.fromObject(response);
	    String result = responsejson.optString("status");
	    String desc = responsejson.optString("msg");
	    if (StringUtils.isBlank(result)) {
		RemindUtils.remind(abilityType, content + ":" + response, "sms");
	    }
	    if (!result.equals("000000")) {// 000000成功
		RemindUtils.remind(abilityType, content + ":" + desc, "sms");
	    }
	} else {
	    RemindUtils.remind(abilityType, content + ":" + "接口响应为空", "sms");
	}
    }

}
